package com.nekonomics
package api.route

import api.dto.response.*
import api.dto.response.RspEncoder.*
import domain.service.util.TokenService
import domain.service.{MerchantService, ProductService}
import domain.validation.RequestValidator

import zio.*
import zio.http.*
import zio.http.Method.*
import zio.json.*


object ProductRoute {
  val routes = baseApiPath / "product" / Routes(
    GET / "sku-cards" -> handler { (req: Request) =>
      for {
        pageNum <- extractParam[Int](req)("pageNum")
        pageSize <- extractParam[Int](req)("pageSize")
        _ <- RequestValidator.checkPageReq(pageNum, pageSize)
        skuCards <- ZIO.serviceWithZIO[ProductService](_.homePageList(pageNum, pageSize))
        rsp = skuCards.toRsp.toJson
      } yield Response.json(rsp)
    },

    GET / "product-detail" -> handler { (req: Request) =>
      for {
        skuId: Long <- extractParam[Long](req)("skuId")
        spu <- ZIO.serviceWithZIO[ProductService](_.getSpu(skuId))
        m <- ZIO.serviceWithZIO[MerchantService](_.findBySpuId(spu.merchantId))
        list <- ZIO.serviceWithZIO[ProductService](_.getSkus4Spu(spu.id))
        skus <- ZIO.foreach(list).apply { (sku, specs) => ZIO.succeed(SkuDetailDto.of(sku, specs)) }
        specs = SkuSpecDto.of(list.flatMap(_._2))
        spuInfo = SpuInfoDto.of(spu)
        merchantInfo = MerchantInfoDto.of(m)
        rsp = ProductDetailDto(merchantInfo, spuInfo, specs, skus).toRsp.toJson
      } yield Response.json(rsp)
    }
  )

}
